package com.zty.xiaomi.server.Controller;

import com.zty.xiaomi.server.Entity.Cart.*;
import com.zty.xiaomi.server.Entity.GoodInfo;
import com.zty.xiaomi.server.Entity.Insurance.Insurance;
import com.zty.xiaomi.server.Entity.User;
import com.zty.xiaomi.server.Service.Cart.CartServiceImp;
import com.zty.xiaomi.server.Service.Good.GoodServiceImp;
import com.zty.xiaomi.server.Service.InsuranceOrder.InsuranceOrderService;
import com.zty.xiaomi.server.Service.InsuranceOrder.InsuranceOrderServiceImp;
import com.zty.xiaomi.server.Service.RegLogin.RegLogServiceImp;
import com.zty.xiaomi.server.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("carts")
public class CartController {

    @Autowired
    private RegLogServiceImp regLogServiceImp;
    @Autowired
    private GoodServiceImp goodServiceImp;
    @Autowired
    private CartServiceImp cartServiceImp;
    @Autowired
    private InsuranceOrderServiceImp insuranceOrderServiceImp;

    @PostMapping("/push")
    public CartResult putShop(@RequestBody pushCart pushcart) throws IOException {
        System.out.println(pushcart);
        CartResult cartResult = new CartResult();
        boolean success = TokenUtil.verify(pushcart.getToken());
        if (success) {
            cartResult.setStatus(0);
            User user = regLogServiceImp.getUserByUserName(pushcart.getUsername().trim());
            String userid = user.getUserid();
            CartGood cartGood = goodServiceImp.getGoodByid(userid, pushcart.getProductId());
            System.out.println(cartGood);
            if (cartGood == null) {
                int goodcount = 1;
                CartGoodInsert goodByidinsert = goodServiceImp.getGoodByidinsert(pushcart.getProductId());
                //取出商品的保险ID
                Integer[] insuranceId = pushcart.getInsuranceId();
                //拼接成字符串
                String new_insurance = "";
                for (int i = 0; i < insuranceId.length; i++) {
                    if (i == insuranceId.length - 1) {
                        new_insurance += insuranceId[i];
                    } else
                        new_insurance += insuranceId[i] + ",";
                }
                List<Insurance> insurances = insuranceOrderServiceImp.getInsuranceById(new_insurance);
                int totalInsurancePrice = 0;
                for (Insurance insurance : insurances
                ) {
                    totalInsurancePrice += insurance.getPrice();
                }
                System.out.println(totalInsurancePrice);
                int totalPrice = (goodcount * goodByidinsert.getPrice()) + totalInsurancePrice;
                goodServiceImp.insCartGood(userid, pushcart.getProductId(), goodByidinsert.getName(),
                        goodByidinsert.getPrice(), goodcount, goodByidinsert.getSubtitle(), goodByidinsert.getProductStock(),
                        goodByidinsert.getStatus(), true, totalPrice, new_insurance, pushcart.getStoreid());
            } else {
                goodServiceImp.updateCartGood(userid, cartGood.getCount() + 1, pushcart.getProductId(), (cartGood.getCount() + 1) * cartGood.getPrice());
            }

            cartProductVoList cartProductVoList = cartServiceImp.getCartProduct(userid);

            int cartTotalPrice = 0;
            boolean selectedAll = true;
            int cartTotalQuantity = 0;
            for (cartProduct cartProduct : cartProductVoList.getList()) {
                cartTotalPrice += cartProduct.getProductTotalPrice();
                if (!cartProduct.isProductSelected()) {
                    selectedAll = false;
                }
                cartTotalQuantity += cartProduct.getCount();
            }


            cartResult.setStatus(0);
            cartResult.setCartTotalPrice(cartTotalPrice);
            cartResult.setCartTotalQuantity(cartTotalQuantity);
            cartResult.setData(cartProductVoList);
            cartResult.setImageHost("www.mi.com");
            cartResult.setSelectedAll(selectedAll);
        } else {
            cartResult.setStatus(10);
        }
        return cartResult;
    }

    @GetMapping("/sum")
    public CartResult getCartSum(@RequestParam("username") String username) throws IOException {
        CartResult cartResult = new CartResult();
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        cartProductVoList cartProductVoList = cartServiceImp.getCartProduct(userid);
        if (cartProductVoList == null) {
            cartResult.setStatus(0);
            cartResult.setCartTotalQuantity(0);
        } else {
            int cartTotalQuantity = 0;
            for (cartProduct cartProduct : cartProductVoList.getList()) {
                cartTotalQuantity += cartProduct.getCount();
            }
            cartResult.setStatus(0);
            cartResult.setCartTotalQuantity(cartTotalQuantity);
        }
        return cartResult;
    }

    @RequestMapping("/del")
    public userCartResult delCarts(@RequestParam("id") int goodid,
                                   @RequestParam("username") String username) throws IOException {
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        goodServiceImp.delGoodByid(userid, goodid);
        userCartResult cartResult = getCarts(username);
        return cartResult;
    }

    @RequestMapping("/getcarts")
    public userCartResult getCarts(@RequestParam("username") String username) throws IOException {
        userCartResult userCartResult = new userCartResult();
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        cartProductVoList cartProductVoList = cartServiceImp.getCartProduct(userid);
        List<Integer> list = cartServiceImp.getcartStore(userid);
        List<CartStroe> cartStroeList = new ArrayList<>();
        for (int storeid : list
        ) {
            CartStroe cartStroe = new CartStroe();
            cartStroe.setStoreid(storeid);
            List<cartProduct> cartProduct = new ArrayList<>();
            if (cartProductVoList != null) {
                for (cartProduct carts : cartProductVoList.getList()
                ) {
                    if (carts.getStoreid() == storeid) {
                        cartProduct.add(carts);
                    }
                    GoodInfo goodInfo = goodServiceImp.getGoodInfo(carts.getGood_id());
                    List<Insurance> insuranceById = insuranceOrderServiceImp.getInsuranceById(carts.getInsurance_id());
                    carts.setInsuranceGoods(insuranceById);
                    carts.setGoodimg(goodInfo.getImage());
                }
            }
            cartStroe.setList(cartProduct);
            cartStroeList.add(cartStroe);

        }

        if (cartProductVoList == null) {
            userCartResult.setStatus(0);
            userCartResult.setCartTotalQuantity(0);
            userCartResult.setSelectedAll(false);
            userCartResult.setImageHost("www.mi.com");
            userCartResult.setCartTotalQuantity(0);
        } else {
            int carttotalPrice = 0;
            boolean selectedall = true;
            int carttotalQuantity = 0;
            for (cartProduct cartProduct : cartProductVoList.getList()) {
                if (cartProduct.isProductSelected())
                    carttotalPrice += cartProduct.getProductTotalPrice();
                if (!cartProduct.isProductSelected()) {
                    selectedall = false;
                }
                carttotalQuantity += cartProduct.getCount();
            }

            userCartResult.setStatus(0);
            userCartResult.setCartTotalPrice(carttotalPrice);
            userCartResult.setCartTotalQuantity(carttotalQuantity);
            userCartResult.setData(cartStroeList);
            userCartResult.setImageHost("www.mi.com");
            userCartResult.setSelectedAll(selectedall);
        }
        return userCartResult;
    }

    @GetMapping("/updatecart")
    public userCartResult getCarts(
            @RequestParam("goodid") int goodid,
            @RequestParam("username") String username,
            @RequestParam("quantity") int count,
            @RequestParam("insurancePrice") int insurancePriceList,
            @RequestParam("selected") boolean selected
    ) throws IOException {
        System.out.println(insurancePriceList);
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        CartGood goodByid = goodServiceImp.getGoodByid(userid, goodid);
        int totalPrice = (goodByid.getPrice() * count) + insurancePriceList;
        goodServiceImp.updaCartNumSel(userid, goodid, count, selected, totalPrice);
        userCartResult carts = getCarts(username);
        return carts;
    }

    @GetMapping("/selectAll")
    public userCartResult SelectAllCart(@RequestParam("username") String username) throws IOException {
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        goodServiceImp.updaCartSelect(userid);
        userCartResult carts = getCarts(username);
        return carts;
    }

    @GetMapping("/unSelectAll")
    public userCartResult unSelectAllCart(@RequestParam("username") String username) throws IOException {
        User user = regLogServiceImp.getUserByUserName(username);
        String userid = user.getUserid();
        goodServiceImp.updaCartunSelect(userid);
        userCartResult carts = getCarts(username);
        carts.setCartTotalQuantity(0);
        carts.setCartTotalPrice(0);
        return carts;
    }
}
